﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.BasicData.EntityFrameworkCore;
using mozhi.smarterp.BasicData.Enums;
using mozhi.smarterp.BasicData.PaymentTerms;
using mozhi.smarterp.BasicData.PaymentTerms.Repositories;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.BasicData.Repositories
{
    public class PaymentTermRepository : EfCoreRepository<BasicDataDbContext, PaymentTerm, Guid>, IPaymentTermRepository
    {
        public PaymentTermRepository(IDbContextProvider<BasicDataDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(string keyword, string code , string name , bool? activated, Guid? excludeId, PaymentTermType type, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var count = await dbContext.Set<PaymentTerm>().AsNoTracking()
                .Where(x => x.Type == type)
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(!name.IsNullOrEmpty(), x => x.Name == name)
                .WhereIf(activated.HasValue, x => x.Activated == activated)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<PaymentTerm>> GetPagedListAsync(string keyword, bool? activated, PaymentTermType type, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var entities = await dbContext.Set<PaymentTerm>().AsNoTracking()
                .Where(x => x.Type == type)
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(activated.HasValue, x => x.Activated == activated)
                .OrderByIf<PaymentTerm, IQueryable<PaymentTerm>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(cancellationToken);

            return entities;
        }
    }
}
